<?php

/**
 * 发票摘要仓库
 * @author wangwx 2015-5-16
 */

namespace common\repositories\myhtsq;

use common\repositories\common\MyscrmContractSyncDeleteDataRepository;
use Exception;
use common\error\ErrorCode;
use common\repositories\BaseRepository;
use common\entities\myhtsq\InvoiceSummaryEntity;
use common\support\StringHelper;

class InvoiceSummaryRepository extends BaseRepository {

    /**
     * 构造函数
     * @param type $config
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 获取所有的摘要信息
     * @return array
     */
    public static function getInvoiceAllSummary() {
        $fields = 'summaryObj.summary_id, summaryObj.summary_type AS Abstract,summaryObj.summary_amount AS Amount,invoiceObj.contract_id AS Receiptguid';
        return InvoiceSummaryEntity::find()
            ->select($fields)
            ->from('myscrm_invoice_summary AS summaryObj')
            ->leftJoin('myscrm_invoice AS invoiceObj', 'summaryObj.invoice_id = invoiceObj.invoice_id')
            ->asArray()
            ->all();
    }

    /**
     * 新增发票摘要
     * @param common\models\myhtsq\InvoiceSummaryModel $invoiceSummaryModel 
     * @return boolean|string 失败返回false，成功返回发票摘要Id
     */
    public static function addInvoiceSummary($invoiceSummaryModel) {
        try {
            $entity = new InvoiceSummaryEntity();

            $data =[];
            if(is_array($invoiceSummaryModel)){
                $data = $invoiceSummaryModel;
            }else if($invoiceSummaryModel instanceof \common\models\myhtsq\InvoiceSummaryModel){
                $data = $invoiceSummaryModel->attributes;
            }
            
            $entity->setAttributes($data);
            if(!(isset($entity->summary_id) && !empty($entity->summary_id))){
                $entity->summary_id = StringHelper::uuid();
            }

           $result = $entity->save();
            if ($result === false) {
                return self::setAndReturn(ErrorCode::ERR_INVOICE_SUMMARY_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_SUMMARY_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 修改发票摘要
     * @param common\models\myhtsq\InvoiceSummaryModel $invoiceSummaryModel 
     * @return boolean|string 失败返回false，成功返回发票摘要Id
     */
    public static function updateInvoiceSummary($invoiceSummaryModel) {
        try {
            $entity = InvoiceSummaryEntity::findOne(['summary_id' => $invoiceSummaryModel->summary_id]);
            if (!isset($entity)) {
                return self::setAndReturn(ErrorCode::ERR_INVOICE_SUMMARY_FORM_SAVE_FAIL, '发票摘要不存在');
            }
            
            $data = [];
            if(is_array($invoiceSummaryModel)){
                $data =  $invoiceSummaryModel;
            }else if($invoiceSummaryModel instanceof \common\models\myhtsq\InvoiceSummaryModel){
                $data = $invoiceSummaryModel->attributes;
            }
            
            $entity->setAttributes($data);
           
            $result = $entity->update();
            if ($result === false) {
                return self::setAndReturn(ErrorCode::ERR_INVOICE_SUMMARY_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->summary_id;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_SUMMARY_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    /**
     * 根据发票ID删除对应的发票摘要信息
     * @param string $invoiceId 发票ID
     * @return boolean 返回true时表示删除成功，否则失败
     */
    public static function deleteInvoiceSummaryByInvoiceId($invoiceId)
    {
        /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
        $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

        $deleteSummaryData = InvoiceSummaryRepository::getInvoiceSummarysByInvoiceId($invoiceId);
        $result = InvoiceSummaryEntity::deleteInvoiceSummaryByInvoiceId($invoiceId);
        if ($result !== true) {
            return self::setAndReturn(InvoiceSummaryEntity::getErrCode());
        }

        if(!empty($deleteSummaryData)){
            foreach ($deleteSummaryData as $deleteSummary){
                $contractSyncDeleteDataRepository->add('myscrm_invoice_summary', 'summary_id', $deleteSummary['summary_id']);
            }
        }

        return true;
    }

    /**
     * 根据发票ID获取发票信息
     * @param string $invoiceId
     * @return array
     */
    public static function getInvoiceSummarysByInvoiceId($invoiceId) {
        return InvoiceSummaryEntity::getInvoiceSummarysByInvoiceId($invoiceId);
    }

}
